package com.dyh.quickdemo.demos.resTemplateInsp;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
@Author=Joey Wheeler
@Date=2020/10/19 16:51
*/
@Configuration
public class RestTemplateEnhanceConf {




    @EnhanceRestTemp
    @Autowired(required = false)
    private List<RestTemplate> restTemplates = Collections.emptyList();
    @Bean
    public SmartInitializingSingleton loadBalancedRestTemplateInitializerDeprecated(
            final ObjectProvider<List<RestTemplateCustomizer>> restTemplateCustomizers) {
        return () -> restTemplateCustomizers.ifAvailable(customizers -> {
            /*明确this 指针*/
            for (RestTemplate restTemplate : RestTemplateEnhanceConf.this.restTemplates) {
                for (RestTemplateCustomizer customizer : customizers) {
                    customizer.customize(restTemplate);
                }
            }
        });
    }
    @Bean
    @ConditionalOnMissingBean
    public RestTemplateCustomizer restTemplateCustomizer(
            final MyRetryIntercepter myRetryIntercepter) {
        return restTemplate -> {
            List<ClientHttpRequestInterceptor> list = new ArrayList<>(
                    restTemplate.getInterceptors());
            list.add(myRetryIntercepter);
            restTemplate.setInterceptors(list);
        };
    }

    @Bean
    MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }

    @Bean
    MyRetryIntercepter myRetryIntercepter(){
        return new MyRetryIntercepter();
    }
}
